package com.laobiao.file_netty_lib.util;

import com.laobiao.file_netty_lib.exception.FileBaseException;

public class ByteUtil{

    /**
     * 替换字节数组指定位置的数据
     * @param src 源数组数据
     * @param replaceData 需替换到源数据数组中的数据
     * @param start 替换起始位置，从0开始
     * @return
     */
    public static byte[] replaceArray(byte[] src,byte[] replaceData,int start){
        if(replaceData.length>src.length || src.length<(start+replaceData.length)){
            throw new ArrayIndexOutOfBoundsException("要替换的数据长度越界！");
        }
        for(byte b : replaceData){
            src[start]=b;
            start++;
        }
        return src;
    }

    /**
     * 合并字节数组
     * @param src1 字节数组1
     * @param src2 字节数组2
     * @return
     */
    public static byte[] mergByte(byte[] src1,byte[] src2){
        if((src1==null || src1.length==0) && (src2==null || src2.length==0)){
            throw new FileBaseException("合并字节数组不能全部都为空！", FileBaseException.ERR_PARAM_NULL);
        }
        if(src1==null || src1.length==0){
            return src2;
        }
        if(src2==null || src2.length==0){
            return src1;
        }
        byte[] b=new byte[src1.length+src2.length];
        return replaceArray(replaceArray(b,src1,0),src2,src1.length);
    }
    
    public static String bSubstring(String s, int length) throws Exception   {   
        byte[] bytes = s.getBytes("UTF-8");     
        int i=0,n=0;  
        while(n<length&&i<bytes.length){  
           i+=2;  
           //判断是否为双字节字符  
         if(bytes[i]==0){  
              n+=1;  
           }else{  
              n+=2;  
           }  
        } 
        return new String(bytes,0,i,"UTF-8");  
    }  


}